package com.wyj;

import com.wyj.mapper.DiscussPostMapper;
import com.wyj.mapper.elasticsearch.DiscussPostRepository;
import com.wyj.pojo.DiscussPost;
import com.wyj.util.RedisKeyUtil;
import com.wyj.util.RedisUtil;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import org.elasticsearch.ElasticsearchTimeoutException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 王永杰
 * @Description 描述该类的做什么用
 * @since 2022/8/6
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = NiukeltApplication.class)
public class textElasticsearch {

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private DiscussPostRepository discussPostRepository;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Test
    public void text01() {
        discussPostRepository.save(discussPostMapper.getDiscussPostById(241));
        discussPostRepository.save(discussPostMapper.getDiscussPostById(242));
        discussPostRepository.save(discussPostMapper.getDiscussPostById(243));


        System.out.println(discussPostMapper.getDiscussPostById(241));
    }

    //插入多条数据
    @Test
    public void textInsertPosts() {
//
    }

    //更新
    @Test
    public void textUpdate() {
        DiscussPost post = discussPostMapper.getDiscussPostById(241);
        post.setContent("王永杰最牛逼");
        discussPostRepository.save(post);
    }

    //删除
    @Test
    public void textDelete() {
        discussPostRepository.deleteAll();
    }

    //按照特殊条件进行查询
    @Test
    public void textQuery() {
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery("互联网寒冬","title","content"))
                .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC)) //type 是否置顶 1是是 0是否
                .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC)) //score 加精
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC)) //创建时间
                .withPageable(PageRequest.of(0,10))
                .withHighlightFields(
                        new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
                        new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
                ).build();

        Page<DiscussPost> page = elasticsearchTemplate.queryForPage(searchQuery, DiscussPost.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {

                SearchHits hits = response.getHits();
                if (hits.getTotalHits() <= 0) {
                    return null;
                }

                List<DiscussPost> list = new ArrayList<>();

                for (SearchHit hit : hits) {
                    DiscussPost post = new DiscussPost();

                    String id = hit.getSourceAsMap().get("id").toString();
                    post.setId(Integer.valueOf(id));

                    String userId = hit.getSourceAsMap().get("userId").toString();
                    post.setUserId(Integer.valueOf(userId));

                    String title = hit.getSourceAsMap().get("title").toString();
                    post.setTitle(title);

                    String content = hit.getSourceAsMap().get("content").toString();
                    post.setContent(content);

                    String status = hit.getSourceAsMap().get("status").toString();
                    post.setStatus(Integer.valueOf(status));

                    String createTime = hit.getSourceAsMap().get("createTime").toString();
                    post.setCreateTime(new Date(Long.valueOf(createTime)));

                    String commentCount = hit.getSourceAsMap().get("commentCount").toString();
                    post.setCommentCount(Integer.valueOf(commentCount));

                    //处理高亮显示出的结果
                    HighlightField titleField = hit.getHighlightFields().get("title");
                    if (titleField != null) {
                        //因为我们搜索的字段 可能太title中有多个  所以我们选择第一个
                        post.setTitle(titleField.getFragments()[0].toString());
                    }

                    HighlightField contentField = hit.getHighlightFields().get("content");

                    if (contentField != null) {
                        post.setContent(contentField.getFragments()[0].toString());
                    }

                    list.add(post);
                }

                return new AggregatedPageImpl(list, pageable,
                        hits.getTotalHits(), response.getAggregations(), response.getScrollId(), hits.getMaxScore());
            }
        });

        //总共有多少元素
        System.out.println(page.getTotalElements());
        //总共有有几页
        System.out.println(page.getTotalPages());
        //当前页是几页
        System.out.println(page.getNumber());
        //每页多少条数据
        System.out.println(page.getSize());

        for (DiscussPost discussPost : page) {
            System.out.println(discussPost);
        }


    }


    @Test
    public void textManyParams() {
       Long nums = null;
        System.out.println(nums);
    }

    @Test
    public void textRedisHl() {

        redisUtil.HyperLogLogAdd("myh","a","b");
        redisUtil.HyperLogLogAdd("myh1","b","c");

        System.out.println(redisUtil.HyperLogLogGetSize("myh"));

        redisUtil.HyperLogLogUnion("myh","myh1");
        System.out.println(redisUtil.HyperLogLogGetSize("myh"));
    }

    @Test
    public void textRedisBitmap() {

//        redisUtil.BitmapAdd("mybitmap",1,false);
//        redisUtil.BitmapAdd("mybitmap",2,false);
//        redisUtil.BitmapAdd("mybitmap",3,false);
//        redisUtil.BitmapAdd("mybitmap",4,true);
//        redisUtil.BitmapAdd("mybitmap",6,true);
//        redisUtil.BitmapAdd("mybitmap",7,true);
//        redisUtil.BitmapAdd("mybitmap",5,true);


//        System.out.println(redisUtil.BitmapGit("mybitmap",6));
//        System.out.println(redisUtil.BitmapGit("mybitmap",1));
        System.out.println("为true的大小:"+redisUtil.BitmapGetTrueSize("mybitmap"));
    }


    @Test
    public void textCalendar() {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date startTime = new Date();

        //相差10秒
        Date endTime = new Date(System.currentTimeMillis()+1000*60*60);

//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(startTime);
//        while (!calendar.getTime().after(endTime)) {
//            String format1 = format.format(calendar.getTime());
//
//            System.out.println(format1);
//
//            //取某个日期之前的一天
//            calendar.add(Calendar.DATE,1);
//
//        }

        System.out.println(format.format(startTime));
        System.out.println(format.format(endTime));

    }


    @Test
    public void textRedis() {
//        redisUtil.sSet("key","1");
//        redisUtil.sSet("key","2");
//        redisUtil.sSet("key","3");

        String postScore = RedisKeyUtil.getPostScore();
        Set<Object> objects = redisUtil.sGet(postScore);
        for (Object object : objects) {
            System.out.println(object);
        }
    }



}
